<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 同步线下商品数据任务
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Http\Controllers\TimedTask\Bill;

use Carbon\Carbon;

use App\Http\Controllers\Controller;

use App\Models\Bill\BillProcess;

use App\Models\Wms\WmsLogistics;

use App\Models\Bill\BillTrace;

use App\Models\ConfigureFunction;

class BillProcessController extends Controller
{

    /**
     * 查询快递100信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function query()
    {

        $tecent_time = date('Y-m-d H:i:s',strtotime('-5 minute'));


        $bill_process = BillProcess::where([['createTime', '<=', $tecent_time]])->orderBy('createTime', 'DESC')->limit(100)->get()->toArray();
//        $bill_process = BillProcess::where(['uuid' => '8E92455A4B16CDB35EF386C6E6721E01'])->limit(100)->get()->toArray();
        if (!$bill_process) {
            return response()->json(['code' => 10000, 'message' => '无可处理订单']);
        }

        foreach ( $bill_process as &$bill )  {

            $process_list = json_decode($bill['process_json'], true);

            if ( isset($process_list['express']) && !empty($process_list['express']) ) {

                //调取快递100接口  获取物流信息
                $express = $this->express($bill['bill_no'], $process_list['express']['number'], $process_list['express']['name']);
                if ($express['code'] != 200) {
                    continue;
                }

                if (in_array($express['data']['state'], array(3, 4, 6))) {
                    unset($process_list['express']);
                } else {
                    $process_list['express']['code'] = $express['data']['state'];
                }

            }

            if (empty($process_list)) {
                BillProcess::where(['uuid' => $bill['uuid']])->delete();
            } else {
                BillProcess::where(['uuid' => $bill['uuid']])->update(['process_json' => json_encode($process_list)]);
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok']);

    }

    public function express($bill_no, $express_number, $express_company){

        if (empty($bill_no)){
            return array('code'=>10001, 'message'=>'订单号不能为空');
        }

        if (empty($express_number)){
            return array('code'=>10002, 'message'=>'快递运单号不能为空');
        }

        if (empty($express_company)){
            return array('code'=>10003, 'message'=>'快递公司名称不能为空');
        }

        $express_data = WmsLogistics::where(['logistics_name' => $express_company])->get()->toArray();
        if (!$express_data) {
            return array('code'=>10004, 'message'=>'快递公司信息未找到');
        }

        $customer = '';
        $key = '';
        $config = ConfigureFunction::getConfigure(20);
        if ($config) {
            $customer = $config['is_customer'];
            $key = $config['is_key'];
        }

        $url = 'https://poll.kuaidi100.com/poll/query.do';

        $post_data = [
            'customer' => $customer,
            'param' => json_encode([
                'com' => $express_data[0]['express_code'],
                'num' => $express_number,
                'from' => '',
                'to' => ''
            ])
        ];

        $post_data['sign'] = strtoupper(md5($post_data['param'].$key.$post_data['customer']));

        $param = '';

        foreach ($post_data as $k=>$v) {
            $param.= "$k=".urlencode($v)."&";
        }
        $post_data=substr($param,0,-1);

        $curl_handler = curl_init();
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_HEADER => false,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36',
            CURLOPT_POST => TRUE,
            CURLOPT_POSTFIELDS => $post_data,
            CURLOPT_SSL_VERIFYPEER => 0
        );
        curl_setopt_array($curl_handler, $options);
        $curl_result = curl_exec($curl_handler);
        if ($curl_result == FALSE) {
            return array('code'=>400, 'message'=>'接口错误');
        }
        curl_close ($curl_handler);
        $data = str_replace("\"",'"',$curl_result );
        $data = json_decode($data,true);

        if ( !empty($data['data']) ) {

            //删除已存在的订单轨迹物流信息
            BillTrace::where(['bill_no' => $bill_no, 'is_express_info' => 1])->delete();

            $return_context = '';
            $logistics_id = $express_data[0]['logistics_id'];
            $logistics_name = $express_data[0]['logistics_name'];
            $website = !empty($express_data[0]['website']) ? $express_data[0]['website'] : '';

            foreach ($data['data'] as $item) {

                $return_context .= $item['context'];
                $time = $item['time'];
                $context = $item['context'];

                $BillTrace = new BillTrace();
                $BillTrace->uuid = makeUuid();
                $BillTrace->timeStamp = Carbon::now();
                $BillTrace->creator = 'system';
                $BillTrace->createTime = $time;
                $BillTrace->bill_no = $bill_no;
                $BillTrace->bill_status = 2;
                $BillTrace->freight_company_id = $logistics_id;
                $BillTrace->freight_company_name = $logistics_name;
                $BillTrace->freight_websit = $website;
                $BillTrace->freight_bill_no = $express_number;
                $BillTrace->content = $context;
                $BillTrace->is_express_info = 1;
                $BillTrace->save();
            }

            $return_data = array(
                'context' => $return_context,
                'state' => $data['state']
            );

            return array('code'=>200, 'message'=>'ok', 'data' => $return_data);

        } else {
            return array('code'=>400, 'message'=>'暂无物流信息');
        }

    }

}